package com.carrental.integration.config;

import feign.Logger;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

/**
 * Feign客户端配置类
 * 用于配置Feign客户端的日志级别、编码器、解码器和请求拦截器
 */
@Configuration
public class FeignConfig {

    /**
     * 配置Feign客户端的日志级别
     * @return Logger.Level
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        // 设置为FULL级别，记录请求和响应的头信息、正文和元数据
        return Logger.Level.FULL;
    }

    /**
     * 配置Feign客户端的编码器
     * @return Encoder
     */
    @Bean
    public Encoder feignEncoder() {
        HttpMessageConverter<Object> jacksonConverter = new MappingJackson2HttpMessageConverter();
        ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
        return new SpringEncoder(objectFactory);
    }

    /**
     * 配置Feign客户端的解码器
     * @return Decoder
     */
    @Bean
    public Decoder feignDecoder() {
        HttpMessageConverter<Object> jacksonConverter = new MappingJackson2HttpMessageConverter();
        ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
        return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
    }

    /**
     * 配置Feign客户端的请求拦截器
     * 用于添加通用的请求头信息
     * @return RequestInterceptor
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            // 添加通用的请求头信息
            requestTemplate.header("Content-Type", "application/json;charset=UTF-8");
            requestTemplate.header("Accept", "application/json");
            // 可以在这里添加认证信息等
        };
    }
} 